import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
import { routes } from '../router';

function filterCachedViews(routes, cachedViews) {
  if (!cachedViews) cachedViews = [];
  routes.forEach((r) => {
    if (r.meta && r.meta.keepAlive) {
      cachedViews.push(r.name);
    }
    if (r.children && r.children.length) {
      filterCachedViews(r.children, cachedViews);
    }
  });
  return cachedViews;
}

export default new Vuex.Store({
  state: {
    homeIsLandingPage: true,
    historyPages: [
      {
        fullPath: '/',
        index: 1,
      },
    ],
    cachedViews: filterCachedViews(routes),
  },
  mutations: {
    /**
     * 操作homeIsLandingPage
     */
    SET_HOME_IS_LANDING_PAGE(state, bool) {
      state.homeIsLandingPage = bool;
    },
    /**
     * 操作historyPages
     * obj格式：{fullPath: '/article?id=1', index: 3} 或 {fullPath: '/article?id=1', scrollY: 0}
     */
    SET_HISTORY_PAGES(state, obj) {
      const page = state.historyPages.find((p) => p.fullPath === obj.fullPath);
      if (!page) {
        let item = { fullPath: obj.fullPath };
        if (obj.hasOwnProperty('index')) {
          item.index = obj.index;
        }
        if (obj.hasOwnProperty('scrollY')) {
          item.scrollY = obj.scrollY;
        }
        state.historyPages.push(item);
      } else {
        if (obj.hasOwnProperty('index')) {
          page.index = obj.index;
        }
        if (obj.hasOwnProperty('scrollY')) {
          page.scrollY = obj.scrollY;
        }
      }
    },
    /**
     * 操作cachedViews
     */
    ADD_CACHED_VIEWS(state, pageName) {
      const cachedViewsSet = new Set(state.cachedViews);
      cachedViewsSet.add(pageName);
      state.cachedViews = [...cachedViewsSet];
    },
    DEL_CACHED_VIEWS(state, pageName) {
      const cachedViewsSet = new Set(state.cachedViews);
      cachedViewsSet.delete(pageName);
      state.cachedViews = [...cachedViewsSet];
    },
  },
  actions: {},
  modules: {},
});
